package com.kotle.mvvmdesign.simpledemo;

import android.app.Application;
import android.arch.lifecycle.MutableLiveData;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.View;
import android.widget.TextView;

import com.kotle.baselib.mvvm.BaseViewModel;
import com.kotle.baselib.mvvm.NetCallBack;
import com.kotle.baselib.recyclerview.BaseViewHolder;
import com.kotle.baselib.recyclerview.SimpleNormalRlvAdapter;
import com.kotle.mvvmdesign.R;

import java.util.List;

/**
 * Created by Kotle on 2017/10/31.
 */

public class MainViewModel extends BaseViewModel<MainNetWork> {

    final static int SHOW_TOAST = 0;
    final static int SET_JOK_ADAPTER = 1;
    public MutableLiveData<RecyclerView.Adapter> adapter=new MutableLiveData<>();

    public MainViewModel(@NonNull Application application) {
        super(application);
    }

    @Override
    public MainNetWork createNetWork() {
        return new MainNetWork();
    }


    void getJokList() {
        getNetWork().getJokList(new NetCallBack<List<JokBean>>() {
            @Override
            public void success(List<JokBean> jokBeans) {
                   setRcvJokAdapter(jokBeans);
            }
        });
    }

    private void setRcvJokAdapter(final List<JokBean> jokBeanList) {
        if (jokBeanList == null || jokBeanList.size() == 0) {
            return;
        }
        SimpleNormalRlvAdapter<JokViewHolder> adapter = new SimpleNormalRlvAdapter<JokViewHolder>(
                R.layout.item_rcv_jok) {
            @Override
            protected JokViewHolder onCreateViewHolder(View itemView) {
                return new JokViewHolder(itemView);
            }

            @Override
            public void onBindViewHolder(JokViewHolder holder, int position) {
                JokBean jokBean = jokBeanList.get(position);
                holder.tvTitle.setText(jokBean.getTitle());
                holder.tvContent.setText(Html.fromHtml(jokBean.getContent()));
            }

            @Override
            public int getItemCount() {
                return jokBeanList.size();
            }
        };
        this.adapter.setValue(adapter);
    }
    @SuppressWarnings("unchecked")
    public void onMethodCall(int methodId, Object... params) {
        switch (methodId) {
            case MainNetWork.NET_WORK_JOK_LIST:
                if (params != null && params[0] != null) {
                    setRcvJokAdapter((List<JokBean>) params[0]);
                }
                break;
        }
    }

    private static class JokViewHolder extends BaseViewHolder {
        private TextView tvContent, tvTitle;

        private JokViewHolder(View itemView) {
            super(itemView);
            tvContent = (TextView) itemView.findViewById(R.id.tv_content);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
        }
    }
}
